import React, {useEffect, useState} from 'react';
import {Breadcrumb, Menu} from 'antd';
import HeaderRight from './header-right';
import {useRequest} from 'ahooks';
import './index.less';
import {getMyMenu} from '@/services/usercenter.ts';
import {useLocation, useNavigate} from "react-router-dom";
import useProjectConfig from "@/hooks/useProjectConfig.ts";
import Cyjc3TempImg from "@/components/Cyjc3TempImg";

const Header: React.FC = () => {
    //当前访问路径
    const {pathname, search} = useLocation();
    const projectConfig = useProjectConfig();
    const navigate = useNavigate();
    // const menuKeyPathMap = useRef<any>({});

    const [menuKeyPathMap, setMenuKeyPathMap] = useState<any>({});
    const [selectedKeys, setSelectedKeys] = useState<any>([]);
    const [breadcrumb, setBreadcrumb] = useState<any>([]);

    const resolveMyMenu = (menus: any[], pid: any, keyPath?: any, namePath?: any) => {
        const filterMenus = menus.filter(item => item.pid === pid).sort((a, b) => a.sort - b.sort);
        return filterMenus.map(item => {
            const antdMenuItem: any = {
                label: item.menuName,
                key: item.code
            }
            const currentNamePath = [...namePath || [], {title: item.menuName}];
            const currentKeyPath = [item.code, ...keyPath || []];
            const children = resolveMyMenu(menus, item.id, currentKeyPath, currentNamePath);
            if (children.length) {
                antdMenuItem.children = children
            } else {
                menuKeyPathMap[currentKeyPath.join()] = {
                    breadcrumbItems: currentNamePath,
                    path: item.url
                }
                setMenuKeyPathMap({...menuKeyPathMap})

                antdMenuItem.path = item.url
            }
            return antdMenuItem;
        })
    }

    const {
        data: topMenus = []
    } = useRequest(
        () =>
            getMyMenu().then((originMenus: any) => {
                const menus: any = resolveMyMenu(originMenus, 0);
                return menus || [];
            })
    );

    //菜单点击事件
    const menuClick = (e: any) => {
        setSelectedKeys(e.keyPath)
        const checkedMenu = menuKeyPathMap[e.keyPath.join()];
        setBreadcrumb(checkedMenu.breadcrumbItems)
        if (checkedMenu.path.startsWith('http')) {
            window.location.href = checkedMenu.path;
            return
        }
        navigate(checkedMenu.path);
    }

    //处理首次进入时菜单选中和面包屑
    useEffect(() => {
        if (!selectedKeys?.length && Object.keys(menuKeyPathMap).length && pathname) {
            for (const key in menuKeyPathMap) {
                const menuItem = menuKeyPathMap[key];
                if (pathname === menuItem.path || (menuItem.path.indexOf('?') !== -1 && `${pathname + search}`.startsWith(menuItem.path))) {
                    setSelectedKeys(key.split(','));
                    setBreadcrumb(menuItem.breadcrumbItems)
                    break;
                }
            }
        }
    }, [pathname, menuKeyPathMap])


    return (
        <header className="layout-header">
            <div className="layout-header-left">
                <a href={projectConfig?.recordVO?.pcHomePageUrl || '/'} target="_self">
                    {/*<img className="logo" src={projectConfig?.configVO?.pcLogo} alt="logo"/>*/}
                    <Cyjc3TempImg className="logo" src={projectConfig?.configVO?.pcLogo}/>
                </a>
            </div>
            <div className="layout-header-right">
                <HeaderRight/>
                <div className={'layout-header-menu inline-block'}>
                    <Menu className={'text-right'}
                          mode="horizontal"
                          id="nav_menu"
                          selectedKeys={selectedKeys}
                          onClick={menuClick}
                          items={topMenus}
                    />
                    <div className="info-line">
                        当前位置：
                        <Breadcrumb separator=">" className={'inline-block'} items={breadcrumb}/>
                    </div>
                </div>
            </div>
        </header>
    );
};
export default Header;
